﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Sector7.Framework.Core;
using Sector7.Framework.Enums;
using Sector7.Framework.DataDictionary.CORS;
using Sector7.Framework.DataDictionary.Utility;
using Sector7.Framework.Utility;
using Sector7.Framework.DataDictionary.Agents;
using Sector7.Framework.Consts;

namespace Sector7.Framework.DataDictionary.Windows
{
    /// <summary>
    /// AddDataElementWindow.xaml 的交互逻辑
    /// </summary>
    public partial class AddDataElementWindow : AddModeWindowBase
    {
        public AddDataElementWindow()
        {
            InitializeComponent();

            FocusedControl = txbElementId;
            //m_addValueFormat = "DE{0:00}.{1:00}.{2:000}.{3:00}"; // DE02.01.001.00
        }

        public S7_DataElement DataElement
        {
            get { return m_entity as S7_DataElement; }
            set { m_entity = value; }
        }

        public S7_DataGroup DataGroup
        {
            get { return m_dataGroup; }
            set { m_dataGroup = value; }
        }

        private S7_DataGroup m_dataGroup = null;
        private List<S7_ValueType> m_valueTypes = null;
        private List<S7_ValueDomain> m_valueDomains = null;

        //protected override void AutoAdd()
        //{
        //    base.AutoAdd();

        //    try
        //    {
        //        string value = txbElementId.Text;
        //        List<string> items = StringUtil.ExtractString(value, m_addValueFormat);

        //        if (!m_isFormated)
        //        {
        //            m_addValueFormat = string.Format(m_addValueFormat, items[0], items[1], "{0:000}", items[3]);
        //            m_isFormated = true;
        //        }

        //        m_addValue = Convert.ToInt32(items[2]);
        //        m_addValue++;
        //    }
        //    catch (Exception e)
        //    {
        //        Log.WriteLine(LogSeverityType.WRN, e);
        //    }
        //}

        protected override void InitializeForCreating()
        {
            txbElementId.Text = AddedValue;
            txbElementName.Text = string.Empty;
            txbDescription.Text = string.Empty;
            txbFormat.Text = string.Empty;
            cbbValueType.SelectedItem = null;
            cbbDomain.SelectedItem = null;

            m_entity = new S7_DataElement();

            base.InitializeForCreating();
        }

        protected override void InitializeForUpdating()
        {
            txbElementId.Text = DataElement.ElementId;
            txbElementName.Text = DataElement.ElementName;
            txbDescription.Text = DataElement.ElementDescription;
            txbFormat.Text = DataElement.ElementFormat;

            cbbValueType.SelectedItem = m_valueTypes.Find(delegate(S7_ValueType __valueType)
            {
                return __valueType.TypeId == DataElement.TypeId;
            });

            if (DataElement.ValueDomain != null)
            {
                cbbDomain.SelectedItem = m_valueDomains.Find(delegate(S7_ValueDomain __valueDomain)
                {
                    return __valueDomain.DomainId == DataElement.DomainId;
                });
            }

            btnContinue.Visibility = Visibility.Hidden;

            base.InitializeForUpdating();
        }

        protected override void InitializeForOthers()
        {
            if (m_dataGroup != null)
            {
                txbGroup.Text = string.Format("{0} {1}", m_dataGroup.GroupIdentifier, m_dataGroup.GroupName);
            }

            base.InitializeForOthers();
        }

        protected override void DoNew()
        {
            base.DoNew();

            S7_DataGroup dataGroup = DataGroupServiceAgent.Get(C_DataGroupIdentifier.NOT_STANDARD_CV);

            var addDomainWindow = new AddValueDomainWindow();
            addDomainWindow.DataGroup = dataGroup;
            addDomainWindow.InitializeWindow(CrudType.Create);
            addDomainWindow.AddSuccess += new EventHandler(addDomainWindow_AddSuccess);

            addDomainWindow.ShowDialog();
        }

        void addDomainWindow_AddSuccess(object sender, EventArgs e)
        {
            var addDomainWindow = sender as AddValueDomainWindow;
            m_valueDomains.Add(addDomainWindow.ValueDomain);

            cbbDomain.Items.Refresh();
        }

        protected override void AddData()
        {
            DataElement.GroupId = m_dataGroup.GroupId;
            DataElement.ElementDescription = txbDescription.Text;
            DataElement.TypeId = Convert.ToInt32(cbbValueType.SelectedValue);

            if (cbbDomain.SelectedItem != null)
            {
                DataElement.DomainId = cbbDomain.SelectedValue.ToString();
                DataElement.ValueDomain = cbbDomain.SelectedItem as S7_ValueDomain;
            }
            else
            {
                DataElement.DomainId = null;
                DataElement.ValueDomain = null;
            }

            switch (m_crud)
            {
                case CrudType.Create:
                    DataElementServiceAgent.Add(DataElement);
                    break;
                case CrudType.Update:
                    bool isChanged = false;
                    EntityDeltaBase delta = GetDelta(C_PrimaryKeyName.DATA_ELEMENT, ref isChanged);

                    if (isChanged)
                    {
                        DataElementServiceAgent.Set(delta);
                    }
                    break;
                default:
                    break;
            }

            base.AddData();
        }

        protected override bool CheckData()
        {
            m_errors.Clear();

            DataElement.ElementId = txbElementId.Text;
            DataElement.ElementName = txbElementName.Text;
            DataElement.ValueType = cbbValueType.SelectedItem as S7_ValueType;
            DataElement.ElementFormat = txbFormat.Text;

            if (string.IsNullOrEmpty(DataElement.ElementId))
            {
                m_errors.Add("数据元标识符", "不能为空！");
            }
            if (string.IsNullOrEmpty(DataElement.ElementName))
            {
                m_errors.Add("数据元名称", "不能为空！");
            }
            if (DataElement.ValueType == null)
            {
                m_errors.Add("数据元值的数据类型", "不能为空！");
            }
            if (string.IsNullOrEmpty(DataElement.ElementFormat))
            {
                m_errors.Add("表示格式", "不能为空！");
            }

            return base.CheckData();
        }        

        protected override void GetData()
        {
            m_valueTypes = ValueTypeServiceAgent.GetAll();
            m_valueDomains = ValueDomainServiceAgent.GetAll();
            
            cbbValueType.ItemsSource = m_valueTypes;
            cbbDomain.ItemsSource = m_valueDomains;
        }

        private void cbbDomain_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Up && e.Key != Key.Down && e.Key != Key.Enter)
            {
                string keyword = cbbDomain.Text;

                if (string.IsNullOrEmpty(keyword))
                {
                    cbbDomain.ItemsSource = m_valueDomains;
                }
                else
                {
                    List<S7_ValueDomain> filteredList = m_valueDomains.FindAll(delegate(S7_ValueDomain valueDomain)
                    {
                        string domainId = valueDomain.DomainId;

                        return domainId.Contains(keyword);
                    });

                    cbbDomain.ItemsSource = filteredList;
                    cbbDomain.Items.Refresh();
                }
            }
        }

        private void cbbDomain_GotFocus(object sender, RoutedEventArgs e)
        {
            cbbDomain.IsDropDownOpen = true;
        }

        private void btnAddDomain_Click(object sender, RoutedEventArgs e)
        {
            DoNew();
        }
    }
}
